import { t } from 'i18next'
import { Button, CheckBox, InnerInputRef, Input, OptionType, Select } from '@kedacom/react-next'
import copy from 'copy-to-clipboard'
import { RightWrap } from '../../components'
import { BtnWrap, Label, Wrap, WrapL } from './style'
import { IconCopy } from '@/components/Icon'
import { fetchGetAllServers } from '@/api/manager/mccMtVideo'
import { useMccStore } from '../../store'
import { useEffect, useMemo, useRef, useState } from 'react'
import {
	fetchDeleteVideo,
	fetchGetMeetingRecorders,
	fetchPauseContinueVideo,
	fetchStartVideo,
} from '@/api/manager/liveVideo'
import Alert, { Confirm } from '@/components/Alert'
import useTimeout from '@/hooks/useTimeout'
import { getRecFileName, useLiveVideoStore } from './store'
import shallow from 'zustand/shallow'
import { formatSeconds } from '@/utils/format'
import { useGlobalStore } from '@/store/global'
import { createRange, regexEnum } from '@/utils'
export default function LiveVideo() {
	const meetingMoid = useMccStore((state) => state.mccInfo.meetingMoid)
	const [serverList, setServerList] = useState<OptionType[]>([
		{
			value: '',
			label: t('请选择'),
		},
	])
	const { enableLive, enableVideo } = useGlobalStore(
		(state) => ({
			enableLive: state.user?.enable_live || 0,
			enableVideo: state.user?.enable_video || 0,
		}),
		shallow
	)
	const data = useLiveVideoStore(
		(state) => ({
			vrs_id: state.vrs_id,
			vrs_name: state.vrs_name,
			id: state.id,
			rec_id: state.rec_id,
			duration: state.duration,
			rec_file: state.rec_file,
			live_url: state.live_url,
			live_qr_code: state.live_qr_code,
			live_password: state.live_password,
			publish_mode: state.publish_mode,
			watermark: state.watermark,
			state: state.state,
			recorder_mode: state.recorder_mode,
			anonymous: state.anonymous,
			dual_stream: state.dual_stream,
			main_stream: state.main_stream,
		}),
		shallow
	)
	const update = useLiveVideoStore((state) => state.update)
	const noVrsId = useMemo(() => data.vrs_id === '', [data.vrs_id])
	const liveStatus = data.recorder_mode === 2 || data.recorder_mode === 3 ? 'on' : 'off'
	const videoStatus =
		data.recorder_mode === 1 || data.recorder_mode === 3 ? (data.state === 2 ? 'pause' : 'on') : 'off'
	const [tips, setTips] = useState(false)
	const [startTimeout, timeoutRef] = useTimeout()
	useEffect(() => {
		if (tips && liveStatus === 'on') {
			setTips(false)
			clearTimeout(timeoutRef.current)
		}
	}, [tips, liveStatus])
	const [tips2, setTips2] = useState(false)
	const [startTimeout2, timeoutRef2] = useTimeout()
	useEffect(() => {
		if (tips2 && videoStatus !== 'off') {
			setTips2(false)
			clearTimeout(timeoutRef2.current)
		}
	}, [tips2, videoStatus])
	const inputPasswordRef = useRef<InnerInputRef>(null)
	const inputVideoRef = useRef<InnerInputRef>(null)
	useEffect(() => {
		Promise.all([fetchGetMeetingRecorders(meetingMoid), fetchGetAllServers({ meeting_id: meetingMoid })]).then(
			(res) => {
				if (res[1]) {
					setServerList(res[1].map((x) => ({ label: x.server_name, value: x.vrs_id })))
					update({ vrs_id: res[1][0].vrs_id })
				}
				if (res[0]) {
					if (res[0].state !== 0) {
						update({ ...res[0], rec_file: getRecFileName(res[0].rec_file) })
					} else {
						update({
							rec_file: getRecFileName(res[0].rec_file),
							live_password: res[0].live_password || '',
							live_url: res[0].live_url || '',
							live_qr_code: res[0].live_qr_code || '',
						})
					}
				}
			}
		)
	}, [])
	const handleStartAll = async () => {
		let valid = await inputVideoRef.current?.valid()
		if (!valid) {
			Alert(inputVideoRef.current?.errorMsg)
			return
		}
		valid = await inputPasswordRef.current?.valid()
		if (!valid) {
			Alert(inputPasswordRef.current?.errorMsg)
			return
		}
		let res = await fetchStartVideo(meetingMoid, {
			vrs_id: data.vrs_id,
			vrs_name: (serverList.find((x) => x.value === data.vrs_id)?.label as string) || '',
			rec_id: data.rec_id,
			rec_file: data.rec_file + '.asf',
			live_password: data.live_password,
			publish_mode: data.publish_mode,
			recorder_mode: 3,
			anonymous: data.anonymous,
			main_stream: data.main_stream,
			dual_stream: data.dual_stream,
		})
		if (!res.success) {
			Alert(res.description || t('操作失败'))
		}
	}
	const handleStopAll = () => {
		Confirm(t('确定结束直播和录像？'), async () => {
			let res = await fetchDeleteVideo(meetingMoid, data.rec_id, { recorder_mode: 3 })
			if (!res.success) {
				Alert(res.description || t('操作失败'))
			}
		})
	}
	const handleStartLive = async () => {
		//直播也需要有录像名
		if (inputVideoRef.current) {
			let valid = await inputVideoRef.current.valid()
			if (!valid) {
				Alert(inputVideoRef.current?.errorMsg)
				return
			}
		}
		let valid = await inputPasswordRef.current?.valid()
		if (!valid) {
			Alert(inputPasswordRef.current?.errorMsg)
			return
		}
		let recorder_mode: 1 | 2 | 3 = 2
		if (data.recorder_mode === 0) {
			recorder_mode = 2
		} else if (data.recorder_mode === 1) {
			recorder_mode = 3
		}
		setTips(true)
		startTimeout(() => setTips(false), 5000)
		let res = await fetchStartVideo(meetingMoid, {
			vrs_id: data.vrs_id,
			vrs_name: (serverList.find((x) => x.value === data.vrs_id)?.label as string) || '',
			rec_id: data.rec_id,
			rec_file: data.rec_file + '.asf',
			live_password: data.live_password,
			publish_mode: data.publish_mode,
			recorder_mode,
			anonymous: data.anonymous,
			main_stream: data.main_stream,
			dual_stream: data.dual_stream,
		})
		if (!res.success) {
			Alert(res.description || t('操作失败'))
		}
	}
	const handleStopLive = () => {
		Confirm(t('确定结束直播？'), async () => {
			let res = await fetchDeleteVideo(meetingMoid, data.rec_id, { recorder_mode: 2 })
			if (!res.success) {
				Alert(res.description || t('操作失败'))
			}
		})
	}
	const handleStartVideo = async () => {
		if (inputVideoRef.current) {
			let valid = await inputVideoRef.current.valid()
			if (!valid) {
				Alert(inputVideoRef.current.errorMsg)
				return
			}
		}
		let recorder_mode: 1 | 2 | 3 = 1
		let rec_file = data.rec_file
		if (data.recorder_mode === 0) {
			recorder_mode = 1
		} else if (data.recorder_mode === 2) {
			recorder_mode = 3
			//已经开启了直播，再单独开录像需重新重新下发录像名
			rec_file = getRecFileName()
		}
		setTips2(true)
		startTimeout2(() => setTips2(false), 5000)
		let res = await fetchStartVideo(meetingMoid, {
			vrs_id: data.vrs_id,
			vrs_name: (serverList.find((x) => x.value === data.vrs_id)?.label as string) || '',
			rec_id: data.rec_id,
			rec_file: rec_file + '.asf',
			live_password: data.live_password,
			publish_mode: data.publish_mode,
			recorder_mode,
			anonymous: data.anonymous,
			main_stream: data.main_stream,
			dual_stream: data.dual_stream,
		})
		if (!res.success) {
			Alert(res.description || t('操作失败'))
		}
	}
	const handleStopVideo = () => {
		Confirm(t('确定结束录像'), async () => {
			let res = await fetchDeleteVideo(meetingMoid, data.rec_id, { recorder_mode: 1 })
			if (!res.success) {
				Alert(res.description || t('操作失败'))
			}
		})
	}
	const handlePauseVideo = async () => {
		let res
		if (videoStatus === 'pause') {
			//继续
			res = await fetchPauseContinueVideo(meetingMoid, data.rec_id, { state: 2 })
		} else {
			//赞停
			res = await fetchPauseContinueVideo(meetingMoid, data.rec_id, { state: 1 })
		}
		if (!res.success) {
			Alert(res.description || t('操作失败'))
		}
	}
	const optionBtn = () => {
		return (
			<BtnWrap>
				{!!(data.recorder_mode === 0 && enableLive && enableVideo) && (
					<Button disabled={noVrsId} onClick={handleStartAll}>
						{t('全部开始')}
					</Button>
				)}
				{!!(data.recorder_mode === 3 && enableLive && enableVideo) && (
					<Button disabled={noVrsId} style={{ color: '#c62619' }} onClick={handleStopAll}>
						{t('全部结束')}
					</Button>
				)}
			</BtnWrap>
		)
	}
	const title = () => {
		if (!enableLive && enableVideo) return t('会议录像')
		if (enableLive && !enableVideo) return t('会议直播')
		return t('录像与直播')
	}

	const nameRef = useRef(null)

	return (
		<RightWrap
			title={title()}
			onBack={() => {
				useMccStore.getState().setCurPage('mcc_main')
			}}
			action={optionBtn()}
		>
			{serverList.length > 1 && (
				<Wrap>
					<Label>{t('录播服务器')}</Label>
					<Select
						width={206}
						placeholder={t('请选择')}
						value={data.vrs_id}
						options={serverList}
						onChange={(e, val) => {
							update({ vrs_id: val })
						}}
					></Select>
				</Wrap>
			)}
			<Wrap>
				<Label>{t('内容选择')}</Label>
				<CheckBox
					className="content-select"
					checked={data.main_stream === 1}
					disabled={true}
					onChange={(e, val) => {
						update({ main_stream: val ? 1 : 0 })
					}}
				>
					{t('主流')}
				</CheckBox>
				<CheckBox
					className="content-select"
					checked={data.dual_stream !== 0}
					disabled={data.recorder_mode !== 0}
					onChange={(e, val) => {
						update({ dual_stream: val ? 1 : 0 })
					}}
				>
					{t('内容共享')}
				</CheckBox>
			</Wrap>
			{!!enableLive && (
				<>
					<Wrap>
						<Label>{t('直播密码')}</Label>
						{liveStatus === 'on' && <span>{data.live_password === '' ? t('无') : data.live_password}</span>}
						{liveStatus === 'off' && (
							<Input
								innerRef={inputPasswordRef}
								maxLength={6}
								width={200}
								placeholder={t('请设定密码')}
								focusMsg={t('输入6个字符，支持大小写字母和数字')}
								value={data.live_password}
								onChange={(e, val) => {
									update({ live_password: val })
								}}
								rule={{
									regular: [
										{
											regex: /^[a-zA-Z0-9]*$/,
											msg: t('直播密码存在非法字符,请重新输入'),
										},
										{
											regex: /^([a-zA-Z0-9]{6})$/,
											msg: t('输入6个字符，支持大小写字母和数字'),
										},
									],
								}}
							/>
						)}
					</Wrap>
					<Wrap style={{ marginBottom: 0 }}>
						<Label>{t('直播')}</Label>
						{liveStatus === 'off' ? (
							<>
								<Button disabled={noVrsId} onClick={handleStartLive}>
									{t('开始直播')}
								</Button>
								{tips && <span className="tips live-tip">{t('正在开始直播...')}</span>}
							</>
						) : (
							<Button
								className="font-red"
								disabled={noVrsId}
								style={{ color: '#c62619' }}
								onClick={handleStopLive}
							>
								{t('结束直播')}
							</Button>
						)}
					</Wrap>
					<Wrap>
						<Label></Label>
						<CheckBox
							checked={data.anonymous === 1}
							disabled={liveStatus === 'on'}
							onChange={(e, value) => {
								update({ anonymous: value ? 1 : 0 })
							}}
						>
							{t('免登录观看直播')}
						</CheckBox>
					</Wrap>
					{data.live_url ? (
						<WrapL>
							<div className="wrap-label">{t('直播地址')}</div>
							<div className="wrap-content">
								<div className="wrap-content-top">
									<span className="live-url" title={data.live_url} ref={nameRef}>
										{data.live_url}
									</span>
									<IconCopy
										className="copy-icon"
										onClick={() => {
											copy(data.live_url || '') && createRange(nameRef.current)
										}}
									></IconCopy>
								</div>
								<div className="qrCode">
									<img className="qrImg" src={data.live_qr_code} alt="" />
									<div>{t('扫码观看直播')}</div>
								</div>
							</div>
						</WrapL>
					) : (
						<div style={{ height: 50 }}></div>
					)}
				</>
			)}
			{!!enableVideo && (
				<>
					<Wrap style={{ marginBottom: 0 }}>
						<Label>{t('录像')}</Label>
						{videoStatus === 'off' ? (
							<>
								<Button disabled={noVrsId} onClick={handleStartVideo}>
									{t('开始录像')}
								</Button>
								{tips2 && <span className="tips video-tip">{t('正在开始录像...')}</span>}
							</>
						) : (
							<>
								{videoStatus === 'pause' ? (
									<Button disabled={noVrsId} onClick={handlePauseVideo}>
										{t('继续录像')}
									</Button>
								) : (
									<Button disabled={noVrsId} onClick={handlePauseVideo}>
										{t('暂停录像')}
									</Button>
								)}
								<Button
									disabled={noVrsId}
									style={{ color: '#c62619', marginLeft: 10 }}
									onClick={handleStopVideo}
								>
									{t('结束录像')}
								</Button>
							</>
						)}
					</Wrap>
					<Wrap>
						<Label></Label>
						<CheckBox
							checked={data.publish_mode === 1}
							disabled={videoStatus !== 'off'}
							onChange={(e, value) => {
								update({ publish_mode: value ? 1 : 0 })
							}}
						>
							{t('发布到视频点播')}
						</CheckBox>
					</Wrap>
					<Wrap>
						<Label>{t('录像文件名')}</Label>
						{(videoStatus !== 'off' || data.recorder_mode === 2) && (
							<span className="wrap-content" title={data.rec_file}>
								{data.rec_file}
							</span>
						)}
						{videoStatus === 'off' && data.recorder_mode !== 2 && (
							<Input
								innerRef={inputVideoRef}
								width={200}
								value={data.rec_file}
								onChange={(e, value) => {
									update({ rec_file: value })
								}}
								maxLength={40}
								rule={{
									required: {
										showIcon: false,
										msg: t('录像文件名不能为空'),
									},
									regular: [
										{
											regex: regexEnum.videoNameIllegal,
											msg: t('录像文件名存在非法字符'),
										},
									],
								}}
							/>
						)}
					</Wrap>
					<Wrap style={{ margin: '0px' }}>
						<Label>{t('录像时长')}</Label>
						{data.duration ? (
							<span className="duration-value">{formatSeconds(data.duration || '0')}</span>
						) : (
							<span className="tips duration-tip">{t('未开始')}</span>
						)}
					</Wrap>
				</>
			)}
		</RightWrap>
	)
}
